package com.dxb.idmr.config;

import com.dxb.idmr.utils.ControllerUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CheckPcMobileInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        if (ControllerUtils.isAjax(request)) {
            return true;
        }
        String path = request.getServletPath();
        //手机访问时跳mobile
        if (!path.startsWith("/mobile/") && ControllerUtils.checkAgentIsMobile(request)) {
            response.sendRedirect("/mobile" + path);
            return false;
        }
        //电脑访问时跳电脑
        if (path.startsWith("/mobile/") && !ControllerUtils.checkAgentIsMobile(request)) {
            response.sendRedirect(path.replaceFirst("/mobile", ""));
            return false;
        }
        // 只有返回true才会继续向下执行，返回false取消当前请求
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}